package com.com.filter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JWTTokenUtil;
import com.util.JsonUtil;

import javax.security.sasl.AuthenticationException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


@WebFilter("*.do")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        System.out.println(" doFilter方法被执行");
        JsonUtil jsonUtil = new JsonUtil();
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson =  gsonBuilder.create();
        JWTTokenUtil jwtTokenUtil = new JWTTokenUtil();
        servletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter out = servletResponse.getWriter();

        try {
            String loginUserInfo =   jwtTokenUtil.getDecodeToken(httpServletRequest);//用JWTToken解密客户传递过的参数access_token

            if (loginUserInfo==null){//表示用户未登录过
                jsonUtil.setCode(1);
                jsonUtil.setMsg("您还未登录，请先登录");
                //提示用户请先登录
                //在过滤器直接返回结果给客户端。。
                out.print(gson.toJson(jsonUtil));
            }else{
                System.out.println("当前的登录用户名为:"+loginUserInfo);
                filterChain.doFilter(servletRequest,servletResponse);//访问下一下过滤器或目标Servlet
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            jsonUtil.setCode(999);
            jsonUtil.setMsg("登录超时，请重新登录");
            //提示用户请先登录
            //在过滤器直接返回结果给客户端。。
            out.print(gson.toJson(jsonUtil));
        }


    }
    @Override
    public void destroy() {

    }
}
